jQuery(function($){

  var BMS_CRM_OBJ = {}

  BMS_CRM_OBJ.DELETE_IMAGE_ID = []

  var SHOW_TYPE = ""

  function getPageView() {
    if ($("#app-container").length > 0 ) {
      return $("#app-container").attr("myView")
    }
  }

  function addImageContainer(num, type){
    console.log("这里传来新image空白的数字是"+ num);
      var html =
              "<div class='fileinput fileinput-new' data-provides='fileinput'>" +
              "<div class='fileinput-preview thumbnail' data-trigger='fileinput'></div>" +
              "<div class='btn-submit-change'>" +
              "<span class='btn btn-file'>" +
              "<span class='fileinput-new iconfont'><i class='fa fa-file-image-o' aria-hidden='true'></i></span>" +
              "<span class='fileinput-exists iconfont'><i class='fa fa-file-image-o' aria-hidden='true'></i></span>"

          var identity = ""
          switch (type) {
              case "store_product":
                  identity = "store_product[images_attributes]"
                  break
              case "room":
                  identity = "store_product[images_attributes]"
                  break
              default:
                  break
          }
          html += "<input class='upload-input upload-image' type='file' name='" + identity + "[" + num + "][image]'>"+
              "</span>" +
              "</div>" +
              "<div class='btn-close iconfont'><i class='fa fa-trash-o' aria-hidden='true'></i></div>" +
              "</div>"
          $(".mssUploadFileContainer").append(html)
  } //end addImageContainer



  BMS_CRM_OBJ.whichImageContainer = function(num) {
    if ( getPageView() == "ROOM-EDIT-PAGE" ) { // 产品
        addImageContainer(num,"store_product")
    }
  }


  if ( $(".mssUploadFileContainer").length > 0 ) {
    var max_count = 3
    var current_img_count = parseInt($(".mssUploadFileContainer").attr("data-image-num"))
    if ( $(".mssUploadFileContainer[data-image-num]").length > 0 && current_img_count < max_count )
     {
        BMS_CRM_OBJ.whichImageContainer(current_img_count) // 新增空白图片（选择图片类型）
      }

    // 点击新增按钮（针对新增和修改页面）
      $(document).on("click",".fileinput .btn-file",function () {
          $(".fileinput .btn-file input").change(function (event) {

              var current_img_count_tmp = 0
              $(".mssUploadFileContainer .fileinput .fileinput-preview img").each(function () {
                  if ( $(this).attr("src") != "" ) {
                      current_img_count_tmp++
                  }
              })

              var img_fill_count = $(".mssUploadFileContainer .fileinput").length

              if ( img_fill_count - current_img_count_tmp > 1 ) {
                  // $(this).
              } else {
                  console.log($(this).parents(".fileinput").find(".fileinput-preview img").length);
                  if ( $(this).parents(".fileinput").find(".fileinput-preview img").length == 0 && img_fill_count < max_count) {
                      if ( getPageView() == "ROOM-EDIT-PAGE" || getPageView() == "ROOM-NEW-PAGE" ) {
                          addImageContainer(img_fill_count, "room")
                      }
                      // 这里可以用length+1获取, 也可以直接获取最后一个
                      $(".mssUploadFileContainer .fileinput:nth-child(" + (img_fill_count + 1) + ")").show()
                  }
              }

          })
      })
      // end 点击新增按钮


      // 点击删除按钮（只针对于修改页面）
      $(".mssUploadFileContainer").on("click",".btn-close",function () {
          var max_count = 3
          var img_total_count = $(".mssUploadFileContainer .fileinput").length // 图片容器个数,包括最后一张空的图片
          var click_index = $(this).parent().index()
          var activity_id // 客房或者餐饮等的id
          var delete_image_id // 删除的图片的id
          if ( getPageView() == "ROOM-EDIT-PAGE") {
              console.log("first");
              activity_id = $("#app-container[myView='ROOM-EDIT-PAGE'] #EditView").attr("data-id")
          }
          delete_image_id = $(this).parent().attr("delete-image-id") // 被删除图片的id

          BMS_CRM_OBJ.DELETE_ID = activity_id // 当前修改的id


          if ( (click_index + 1) < img_total_count && img_total_count >1 && img_total_count < max_count ) {
            console.log("一　１" );
            console.log(img_total_count - 2);
              $(this).parent().remove() // 移除图片
              BMS_CRM_OBJ.DELETE_IMAGE_ID.push(delete_image_id)
              BMS_CRM_OBJ.editLastImageIndex( img_total_count-2 )
          }
          else if ( (click_index + 1) < img_total_count && img_total_count == max_count ) {
              if ( $(".mssUploadFileContainer .fileinput:nth-child(6) .thumbnail img").length > 0) {
                console.log("二 1"+ img_total_count);
                  $(this).parent().remove() // 移除图片
                  BMS_CRM_OBJ.DELETE_IMAGE_ID.push(delete_image_id)

                  BMS_CRM_OBJ.whichImageContainer(img_total_count) // 新增空白图片（选择图片类型）
                  BMS_CRM_OBJ.editLastImageIndex( img_total_count-1 )

              } else {
                console.log("二 2"+ img_total_count);
                  $(this).parent().remove() // 移除图片
                  BMS_CRM_OBJ.DELETE_IMAGE_ID.push(delete_image_id)
                  BMS_CRM_OBJ.editLastImageIndex( img_total_count-2 )
              }
          }
          else if ( (click_index + 1) == img_total_count && img_total_count == max_count ) {
              if ( $(".mssUploadFileContainer .fileinput:nth-child(" + max_count + ") .thumbnail img").length > 0) {
                console.log("三 1"+ img_total_count);
                  $(this).parent().remove() // 移除图片
                  BMS_CRM_OBJ.DELETE_IMAGE_ID.push(delete_image_id)

                  BMS_CRM_OBJ.whichImageContainer(img_total_count) // 新增空白图片（选择图片类型）
                  BMS_CRM_OBJ.editLastImageIndex( img_total_count-1 )
              }

          }

      })
      // end 点击删除按钮
  } // if 判断结束


  BMS_CRM_OBJ.editLastImageIndex = function (num) {
    if ( getPageView() == "ROOM-EDIT-PAGE" ) { // 客房
        $(".mssUploadFileContainer .fileinput:last-child .upload-image").attr("name","store_product[images_attributes][" + num + "][image]")
    }
  }


    //点击是否优惠价
    $(document).on("change", "div#app-container[myApp='ROOM-NEW-EDIT-PAGE'] select.js-vipable-change", function(){
      var status = $(this).val();
      $("div.js-vipprice-change").toggle();
    })


    // button commit in edit page
    if ( getPageView() == "ROOM-EDIT-PAGE" ) {
      $(document).on("click","#app-container[myApp='ROOM-NEW-EDIT-PAGE'] .button-submit-cancle .button-submit",function () {
        // 客房编辑页面删除图片
        if (BMS_CRM_OBJ.DELETE_ID != undefined && BMS_CRM_OBJ.DELETE_IMAGE_ID.length > 0) {
          // 如果已经点击删除按钮(至少删除一副图片)
          var csrf = $("input#js-ruiqu-store-product-edit").val();
          $.ajax({
            url: "/ruiqu/store/products/"+ BMS_CRM_OBJ.DELETE_ID +"/remove_image",
            type: "delete",
            dataType: "json",
            headers: {
                      'X-CSRF-Token': csrf
                    },
            data: {image_ids: BMS_CRM_OBJ.DELETE_IMAGE_ID},
            success: function (data) {
                console.log("删除成功")
            },
            error: function () {
                console.log("删除失败")
            }
          })
        }
      })
    }

})
